package com.example.validator;

import com.example.anno.EnumValidAnno;
import com.example.constant.ValueEnum;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;

@Component
public class EnumValueValidator implements ConstraintValidator<EnumValidAnno, Integer> {

    Class<? extends ValueEnum> valueEnum;

    @Override
    public void initialize(EnumValidAnno constraintAnnotation) {
        valueEnum = constraintAnnotation.enumValue();
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        ValueEnum[] enumConstants = valueEnum.getEnumConstants();
        return Arrays.stream(enumConstants).anyMatch(e -> e.getValue() == value);
    }
}
